// pinia 和 vuex 都有一个通病 页面刷新状态会丢失

import { PiniaPluginContext, storeToRefs } from "pinia";
import { toRaw } from "vue";
const _piniaKey = '__PINIAKEY__';
// 我们可以写一个pinia 插件缓存他的值
type Options = Record<string, any>;
export const piniaPlugin = function(options: Options) {
    return (context: PiniaPluginContext) => {
        const { store } = context;
        console.log('PiniaPluginContext:', context, 'store:', store);
        const data = getStorage(`${options?.key ?? _piniaKey}-${store.$id}`);
        store.$subscribe(() => {
            setStorage(`${options?.key ?? _piniaKey}-${store.$id}`, toRaw(store.$state));
        });
        return {
            ...store.$state,
            ...data
        };
    };
};

const setStorage = function(key: string, value: any):void {
    localStorage.setItem(key, JSON.stringify(value));
};

const getStorage = function(key: string): any {
    return localStorage.getItem(key) ? JSON.parse(localStorage.getItem(key)!)  : {};
};